package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/wechat"
	"math/rand"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"shangyuapi/utils"
	"strconv"
	"time"
)

func Thalicoins(ctx *gin.Context) {

	var users []models.Thalicoin
	data_source.Db.Order("price desc").Find(&users)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return
}

var (
	mchID  string = "1624351569"                       // 商户号
	apiKey string = "Z3vX4X0VVfnNWdeclj4HXc9nw08uIYw0" //
	pturl  string = "https://shanyu.jiayixunfang.cn"   //
)

type PayBody struct {
	Thalicoinid int64 `json:"thalicoinid" from:"thalicoinid"`
	Uid         int64 `json:"uid" from:"uid"`
}

// 微信支付-充值星币
func Wechatpay(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)
	thalicoinid := request.Thalicoinid
	uid := request.Uid

	var th models.Thalicoin
	data_source.Db.Where("id = ?", thalicoinid).First(&th)

	var buyxingbis []models.Buyxingbi
	data_source.Db.Where("uid = ?", uid).Where("status = 2").Find(&buyxingbis)
	if len(buyxingbis) > 0 {
		th.Jscoin = 0

		if th.Num > 0 {
			var num int64
			for _, b := range buyxingbis {
				if b.Thalicoinid == thalicoinid {
					num = num + 1
				}
			}
			if th.Num <= num {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    400,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "无法享受该优惠",
				})
				return
			}
		}

	}

	orderno := Generateto(time.Time{})

	buyxingbiadd := models.Buyxingbi{
		Uid:         uid,
		Thalicoinid: thalicoinid,
		Price:       th.Price,
		Coin:        th.Coin,
		Jscoin:      th.Jscoin,
		Addtime:     time.Now().Unix(),
		Status:      1,
		Orderno:     orderno,
	}
	data_source.Db.Create(&buyxingbiadd)
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)

	client := wechat.NewClient(appID, mchID, apiKey, true)
	client.SetCountry(wechat.China)
	client.AddCertPemFilePath("upload/apiclient_cert.pem", "upload/apiclient_key.pem")
	money2 := int(th.Price * 100)
	//money2 := 1
	//初始化参数Map
	bm := make(gopay.BodyMap)
	//OrderNo := util.RandomString(32)

	bm.Set("nonce_str", Generateto(time.Time{})).
		Set("body", "商品购买").
		Set("out_trade_no", orderno).
		Set("total_fee", money2).
		Set("spbill_create_ip", ctx.ClientIP()).
		Set("notify_url", pturl+"/user/wechatNotify").
		Set("trade_type", wechat.TradeType_JsApi).
		Set("sign_type", wechat.SignType_MD5).
		Set("openid", user.RoutineOpenid)

	//请求支付下单，成功后得到结果
	wxRsp, err := client.UnifiedOrder(ctx, bm)
	fmt.Println(wxRsp)
	timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
	packages := "prepay_id=" + wxRsp.PrepayId // 此处的 wxRsp.PrepayId ,统一下单成功后得到
	paySign := ""
	paySign = wechat.GetJsapiPaySign(appID, wxRsp.NonceStr, packages, wechat.SignType_MD5, timeStamp, apiKey)
	//fmt.Println(paySign)
	//return
	data := map[string]interface{}{
		"appId":     wxRsp.Appid,
		"timeStamp": timeStamp,
		"nonceStr":  wxRsp.NonceStr,
		"package":   packages,
		"signType":  wechat.SignType_MD5,
		"sign":      paySign,
		"order_no":  orderno, // 订单号
	}

	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "稍后再试",
			"data": gin.H{},
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    data,
	})
	return
}

// @Summary 微信支付回调
// @Produce  json
// @Success 200 {string} string "success"
// @Router /v1/wechat_notify [post]
func WechatNotify(c *gin.Context) {
	notifyRsp, err := wechat.ParseNotifyToBodyMap(c.Request)
	fmt.Println(notifyRsp)
	if err != nil {
		c.String(200, "error")
		return
	}
	ok, errSign := wechat.VerifySign(apiKey, wechat.SignType_MD5, notifyRsp)
	if ok { // 验证成功
		fmt.Println("errSign = ", errSign)
		fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupay(notifyRsp["out_trade_no"].(string))
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}

// 支付完成
func Zhifupay(order string) {

	orderup := models.Buyxingbi{
		Status: 2,
	}
	data_source.Db.Where("orderno = ?", order).Updates(&orderup)

	var orders models.Buyxingbi
	data_source.Db.Where("orderno = ?", order).First(&orders)
	var user models.User
	data_source.Db.Where("id = ?", orders.Uid).First(&user)
	//data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).Update("updatetime", time.Now().Unix())
	xingbi := models.Userxingbi{
		Uid:     orders.Uid,
		Price:   orders.Coin + orders.Jscoin,
		Status:  2,
		Title:   "查看异性详情",
		Addtime: time.Now().Unix(),
		Dqprice: user.Xingbi + orders.Coin + orders.Jscoin,
	}
	data_source.Db.Create(&xingbi)

	data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).Update("xingbi", user.Xingbi+orders.Coin+orders.Jscoin)

}

var ordernum int64

func Generateto(t time.Time) string {
	// 生成当前日期部分（例如：20231008）
	datePart := time.Now().UnixNano()
	// 生成随机数部分（4位随机数）
	rand.Seed(time.Now().UnixNano())
	randomPart := fmt.Sprintf("%04d", rand.Intn(10000))
	// 最终的订单号由前缀、日期和随机数部分组成
	orderNumber := utils.Int64string(datePart) + randomPart
	return orderNumber
}
